package com.pandora.util;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.pandora.exception.UtilException;


public class PropertyUtil {
	public static Map<String, String> getProps(String resourcePath) throws UtilException {
		File pkageFile=FileUtil.getResourcAsFile(resourcePath);
		File[] propFiles=getPropFiles(pkageFile);
		Map<String, String> propsMap=new HashMap<String, String>();
		if (propFiles==null) {
			return null;
		}
		for (File file : propFiles) {
			Map<String, String> temp=getProps(file);
			propsMap.putAll(temp);
		}
		return propsMap;
	}
	public static Map<String, String> getProps(File file) throws UtilException {
		Map<String, String> propsMap=new HashMap<String, String>();
		InputStream in=FileUtil.getResourcAsStream(file);
		Properties properties=new Properties();
		try {
			properties.load(in);
		} catch (IOException e) {
			throw new UtilException("properties文件流读取失败",e);
		}
		for (Object key : properties.keySet()) {
			String keyStr=key.toString();
			String value=properties.getProperty(keyStr);
			propsMap.put(keyStr, value);
		}
		return propsMap;
		
	}
	private static File[] getPropFiles(File pkageFile) {
		final List<File[]> propFilesList=new ArrayList<File[]>();
		if (pkageFile.isDirectory()) {
			//拿到classpath目录下的所有properties文件
			File[] propFiles=pkageFile.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					if (name.endsWith(".properties")) {
						return true;
					}else {
						String childFolderName=dir.getAbsolutePath()+File.separator+name;
							try {
								File childFolderFile=FileUtil.getResourcAsFile(childFolderName);
								File[] folderSpropFiles=getPropFiles(childFolderFile);
								propFilesList.add(folderSpropFiles);
							} catch (UtilException e) {
								e.printStackTrace();
							}
						return false;
					}
				}
				
			});
			propFilesList.add(propFiles);
		}else {
			if (pkageFile.getName().endsWith(".properties")) {
				File[] propFile=new File[]{pkageFile};
				propFilesList.add(propFile);
			}
		}
		//合并list<File[]>中的properties文件为一个File数组
		List<File> temp=new ArrayList<File>();
		for (File[] file : propFilesList) {
			for (File file2 : file) {
				temp.add(file2);
			}
		}
		File[] rt=new File[temp.size()];
		rt=temp.toArray(rt);
		return rt ;
	}
}
